<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>localStorage</title>
</head>
<body>

<div>
    <label id="message">localStorage</label>
    <button onclick="clearLocalStorage();">清空localStorage</button>
</div>

<script>
    function clearLocalStorage() {
        localStorage.clear();
        alert('清空成功');
    }

    window.addEventListener('message', function (e) {
        if (e.source != window.parent) {
            return;
        }
        const data = e.data;
        console.log(data);
        if (data && typeof (data) === 'string') {
            const arr = data.split(':');
            const ope = arr[0];
            if (ope == 'set') {
                localStorage.setItem(arr[1], arr[2]);
                console.log('localStorage setItem success:', arr[1], arr[2]);
            } else if (ope == 'get') {
                window.parent.postMessage(localStorage.getItem(arr[1]), '*')
                console.log('localStorage getItem success:', arr[1]);
            } else if (ope == 'remove') {
                localStorage.removeItem(arr[1]);
                console.log('localStorage removeItem success:', arr[1]);
            } else {
                console.error('error command');
            }
        } else {
            console.error('error command');
        }
    }, false);
</script>
</body>
</html>
